package com.lagou.controller;

import com.lagou.service.UserService;
import com.netflix.discovery.converters.Auto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@RequestMapping("/user")
@RefreshScope
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 注册接口：-1后台服务异常 0.成功 1.验证码错误 2.验证码超时 3.未发送过验证码 4.邮箱已经注册
     *
     * @param email
     * @param password
     * @param code
     * @return
     */
    @GetMapping("/register/{email}/{password}/{code}")
    @ResponseBody
    public String register(@PathVariable String email, @PathVariable String password, @PathVariable String code, HttpServletResponse response) {
        return userService.register(email, password, code, response);
    }

    /**
     * 是否已注册，根据邮箱判断,true代表已经注册过，false代表尚未注册
     *
     * @param email
     * @return
     */
    @GetMapping("/isRegistered/{email}")
    @ResponseBody
    public boolean isRegistered(@PathVariable String email) {
        return userService.isRegistered(email);
    }

    /**
     * 登录接口，验证用户名密码合法性，根据用户名和密码生成token，token存入数据库，并写入cookie中，
     * 登录成功返回邮箱地址，重定向到欢迎⻚页
     *
     * @param email
     * @param password
     * @return
     */
    @GetMapping("/login/{email}/{password}")
    @ResponseBody
    public boolean login(@PathVariable String email, @PathVariable String password, HttpServletResponse response) {
        return userService.login(email, password, response);
//        try {
//            response.sendRedirect("http://www.test.com/static/login.html");
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }

    /**
     * 根据token查询用户登录邮箱接口
     *
     * @param token
     * @return
     */
    @GetMapping("/info/{token}")
    @ResponseBody
    public String info(@PathVariable String token) {
        return userService.info(token);
    }

}
